package com.neborosoft.FlyingDog.android.playing;

import android.app.Activity;
import android.os.Parcelable;
import android.view.MenuItem;
import android.os.Parcelable;import android.view.MenuItem;import android.view.SubMenu;import com.neborosoft.FlyingDog.R;
import com.neborosoft.FlyingDog.android.gui.adapters.listview.SongsPlayListAdapter;
import com.neborosoft.FlyingDog.android.playing.modes.*;
import com.neborosoft.FlyingDog.logic.database.AudioDataManager;
import com.neborosoft.FlyingDog.logic.database.LocalAudioDataBase;
import com.neborosoft.FlyingDog.logic.database.providers.*;
import com.neborosoft.android.events.HistoryManager;
import com.neborosoft.FlyingDog.logic.database.providers.AlbumsTree;
import com.neborosoft.FlyingDog.logic.database.providers.ArtistTree;
import com.neborosoft.FlyingDog.logic.database.providers.GenresTree;
import com.neborosoft.FlyingDog.logic.database.providers.PlayListsTree;
import com.neborosoft.android.events.HistoryManager;
import com.neborosoft.android.gui.AndroidMenuManager;
import com.neborosoft.android.gui.Gui;
import com.neborosoft.android.gui.adapters.listview.ViewArrayAdapter;
import com.neborosoft.android.gui.search.SearchDialog;
import com.neborosoft.android.gui.views.LayoutRadioButtonGroup;
import com.neborosoft.android.gui.wrappers.ListViewSwitcher;
import com.neborosoft.lib.handlers.OnHardwareBackPressed;

import java.util.Comparator;import java.util.List;
import java.util.Map;
/**
 * Created with IntelliJ IDEA.
 * User: CM
 * Date: 04.11.12
 * Time: 15:00
 * To change this template use File | Settings | File Templates.
 */
public class PlayingModeManager {
    private static final HistoryManager HISTORY_MANAGER = HistoryManager.getInstance();
    private static final AndroidMenuManager ANDROID_MENU_MANAGER = AndroidMenuManager.getInstance();

    private Activity activity;
    private ListViewSwitcher listViewSwitcher;

    private LayoutRadioButtonGroup.LayoutRadioButton
        albumsButton,allSongsButton,artistsButton,playListsButton,genresButton,countriesButton,moodButton;

    private LayoutRadioButtonGroup switcher;

    private PlayingMode[] playingModes;

    private AllSongsPlayingMode allSongsPlayingMode;

    private int savedPlayingModeIndex = -1;
    private Object savedPlayingModeState;
    private boolean shouldOnSelectionChangedListenerBeExecuted = false;

    private LayoutRadioButtonGroup.LayoutRadioButton getLayoutRadioButton(int id){
        LayoutRadioButtonGroup.LayoutRadioButton button =
                (LayoutRadioButtonGroup.LayoutRadioButton)activity.findViewById(id);
        return button;
    }

    private void initPlayingModes(){
        switcher = (LayoutRadioButtonGroup)activity.findViewById(R.id.playlistSwitcherContent);

        int childCount = switcher.getChildCount();
        playingModes = new PlayingMode[childCount];

        allSongsButton = getLayoutRadioButton(R.id.allSongsPlayListButton);
        allSongsPlayingMode = new AllSongsPlayingMode(activity, listViewSwitcher);
        playingModes[allSongsButton.getIndex()] = allSongsPlayingMode;

        genresButton = getLayoutRadioButton(R.id.genresPlayListButton);
        playingModes[genresButton.getIndex()] =
                new GenresMode(activity, listViewSwitcher, new GenresTree());
        playListsButton = getLayoutRadioButton(R.id.playlistsPlayListButton);
        playingModes[playListsButton.getIndex()] =
                new PlayListsMode(activity, listViewSwitcher, new PlayListsTree());
        albumsButton = getLayoutRadioButton(R.id.albumsPlayListButton);
        playingModes[albumsButton.getIndex()] = new AlbumsMode(activity, listViewSwitcher, new AlbumsTree());
        artistsButton = getLayoutRadioButton(R.id.artistsPlayListButton);
        playingModes[artistsButton.getIndex()] = new ArtistsMode(activity, listViewSwitcher, new ArtistTree());
        countriesButton = getLayoutRadioButton(R.id.countriesPlayListButton);
        playingModes[countriesButton.getIndex()] = new CountriesMode(activity, listViewSwitcher,
                new CountriesTree());
        moodButton = getLayoutRadioButton(R.id.moodPlayListButton);
        playingModes[moodButton.getIndex()] = new MoodMode(activity, listViewSwitcher, new MoodTree());

        switcher.setOnSelectedChangedListener(new OnSelectionChangedHandler());
    }

    public PlayingModeManager(Activity activity){
        this.activity = activity;

        listViewSwitcher = new ListViewSwitcher(activity, R.id.playListModeSwitcher);

        searchDialog = (SearchDialog)activity.findViewById(R.id.searchDialog);
        searchDialog.setSearchHandler(searchHandler);

        initPlayingModes();

        ANDROID_MENU_MANAGER.setOnMenuItemClickListener(R.id.returnToCurrentPlaylist,
                new AndroidMenuManager.OnMenuItemClick() {
            @Override
            public void onClick(MenuItem menuItem) {
                onGoToCurrentPlaylist();
            }
        });

        AudioDataManager.getInstance().startAlbumArtsUpdating(
                new LocalAudioDataBase.OnArtsUpdatingFinished() {
            @Override
            public void onFinished() {
                ViewArrayAdapter adapter = listViewSwitcher.getAdapter();
                adapter.notifyDataSetChanged();
            }
        });
    }

    public PlayingMode getPlayingMode() {
        int index = switcher.getSelectedItemIndex();
        return playingModes[index];
    }

    private SearchDialog searchDialog;
    private SearchDialog.SearchHandler searchHandler = new SearchDialog.SearchHandler(){
        @Override
        public void onSearchFinished(Object searchResult) {
            PlayingMode playingMode = getPlayingMode();
            playingMode.onSearchFinished(searchResult);
        }

        @Override
        public List getSuggestions(String query) {
            PlayingMode playingMode = getPlayingMode();
            return playingMode.getSearchSuggestions(query);
        }

        @Override
        public Object search(String query) {
            PlayingMode playingMode = getPlayingMode();
            return playingMode.search(query);
        }

        @Override
        public void onSkipSearch() {
            PlayingMode playingMode = getPlayingMode();
            playingMode.onSkipSearch();
        }
    };

    private void executeOnOtherModeSelected(final LayoutRadioButtonGroup.LayoutRadioButton old){
        if(old != null){
            int oldIndex = old.getIndex();
            PlayingMode oldPlayingMode = playingModes[oldIndex];
            oldPlayingMode.onAnotherModeSelected();
        }
    }

    private class OnSelectionChangedHandler implements LayoutRadioButtonGroup.OnSelectedChanged{
        private Parcelable listViewState = null;

        @Override
        public void onSelectedChanged(boolean fromUser,
                                      LayoutRadioButtonGroup.LayoutRadioButton item,
                                      final LayoutRadioButtonGroup.LayoutRadioButton old)
        {
            if(shouldOnSelectionChangedListenerBeExecuted){
                executeOnOtherModeSelected(old);
                return;
            }

            int index = item.getIndex();
            PlayingMode playingMode = playingModes[index];
            if(playingMode == null){
                old.select();
                return;
            }

            executeOnOtherModeSelected(old);

            final Parcelable listViewState = playingMode.getListViewState();
            if(this.listViewState != null){
                listViewSwitcher.getListView().onRestoreInstanceState(listViewState);
            }

            playingMode.showInListView(this.listViewState != null);

            this.listViewState = null;

            boolean isSearchingAllowed = playingMode.isSearchAllowed();
            Gui.setViewVisibility(searchDialog,isSearchingAllowed);

            if(fromUser){
                HISTORY_MANAGER.pushHardwareBackPressedListener(new OnHardwareBackPressed() {
                    @Override
                    public void onBack() {
                        OnSelectionChangedHandler.this.listViewState = listViewState;
                        old.select();
                    }
                });
            }
        }
    }

    private void onGoToCurrentPlaylist(){
        SongsPlayListAdapter selectedSongsPlayListAdapter = SongsPlayListAdapter.getSelectedSongsAdapter();
        if(selectedSongsPlayListAdapter == null){
            return;
        }

        ViewArrayAdapter adapter = listViewSwitcher.getAdapter();
        if(adapter == selectedSongsPlayListAdapter){
            selectedSongsPlayListAdapter.scrollListViewToSelectedIndex();
            return;
        }

        saveState();
        HISTORY_MANAGER.pushHardwareBackPressedListener(new OnHardwareBackPressed() {
            @Override
            public void onBack() {
                restoreState();
            }
        });

        shouldOnSelectionChangedListenerBeExecuted = true;
        allSongsButton.select();
        allSongsPlayingMode.showSelectedPlaylist();
        shouldOnSelectionChangedListenerBeExecuted = false;
    }

    private void saveState(){
        savedPlayingModeIndex = switcher.getSelectedItemIndex();
        PlayingMode playingMode = playingModes[savedPlayingModeIndex];
        savedPlayingModeState = playingMode.getState();
        if(savedPlayingModeState == null){
            throw new NullPointerException();
        }
    }

    private void restoreState(){
        if(savedPlayingModeIndex == -1){
            HISTORY_MANAGER.popHardwareBackPressedListener();
        } else {
            PlayingMode playingMode = playingModes[savedPlayingModeIndex];
            LayoutRadioButtonGroup.LayoutRadioButton radioButton =
                    (LayoutRadioButtonGroup.LayoutRadioButton)switcher.getChildAt(savedPlayingModeIndex);

            shouldOnSelectionChangedListenerBeExecuted = true;
            radioButton.select();
            shouldOnSelectionChangedListenerBeExecuted = false;

            playingMode.restoreState(savedPlayingModeState);
            savedPlayingModeIndex = -1;
            savedPlayingModeState = null;
        }
    }

    private void onSortMenuItemClick(MenuItem item){
        PlayingMode playingMode = getPlayingMode();

        if(!item.hasSubMenu()){
            return;
        }

        SubMenu subMenu = item.getSubMenu();
    }

    private void updateSortingComparator(){

    }
}
